package io.finer.erp.jeecg.bas.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.ZrkUserCustomer;
import io.finer.erp.jeecg.bas.mapper.ZrkUserCustomerMapper;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.IZrkUserCustomerService;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 业务员客户分配表
 * @Author: jeecg-boot
 * @Date:   2020-08-22
 * @Version: V1.0
 */
@Service
@Slf4j
public class ZrkUserCustomerServiceImpl extends ServiceImpl<ZrkUserCustomerMapper, ZrkUserCustomer> implements IZrkUserCustomerService {

	@Autowired
	private IBasCustomerService bcService;
	
	@Override
	public ZrkUserCustomer getByCustomerId(String customId) {
		LambdaQueryWrapper<ZrkUserCustomer> query = new LambdaQueryWrapper<>();
		query.eq(ZrkUserCustomer::getCustomerId, customId);
		return getOne(query);
	}

	@Override
	@Transactional
	public boolean saveUserCustomer(ZrkUserCustomer zrkUserCustomer) {
		// TODO Auto-generated method stub
		//添加之前判断客户是否已经分配
		LambdaQueryWrapper<ZrkUserCustomer> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ZrkUserCustomer::getCustomerId, zrkUserCustomer.getCustomerId());
		List<ZrkUserCustomer> zrkUserCustomerList = this.list(queryWrapper);
		//判断该客户是否在分配表中
		if(null!=zrkUserCustomerList&&zrkUserCustomerList.size()>0) {
			throw new RuntimeException("客户已经分配了业务员！");
		}else {
			//若该客户未被分配，将该客户分配时修改他的分配状态为1
			BasCustomer basCustomer = bcService.getById(zrkUserCustomer.getCustomerId());
			if(null!=basCustomer) {
				//将客户分配状态改为已分配，防止重复分配该客户
				basCustomer.setIsAllocated(2);
				bcService.updateById(basCustomer);
			}
			return this.save(zrkUserCustomer);
		}
	}

	@Override
	@Transactional
	public boolean updateUserCustomer(ZrkUserCustomer zrkUserCustomer) {
		// TODO Auto-generated method stub
		ZrkUserCustomer userCustomer = this.getById(zrkUserCustomer.getId());
		//判断该客户是否在分配表中
		if(null!=userCustomer) {
			if(!StringUtils.equals(userCustomer.getUserId(), zrkUserCustomer.getUserId())) {
				userCustomer.setUserId(zrkUserCustomer.getUserId());
			}
			if(!StringUtils.equals(userCustomer.getCustomerId(), zrkUserCustomer.getCustomerId())) {
				LambdaQueryWrapper<ZrkUserCustomer> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(ZrkUserCustomer::getCustomerId, zrkUserCustomer.getCustomerId());
				List<ZrkUserCustomer> zrkUserCustomerList = this.list(queryWrapper);
				//判断该客户是否在分配表中
				if(null!=zrkUserCustomerList&&zrkUserCustomerList.size()>0) {
					throw new RuntimeException("该客户已经分配了业务员！");
				}
				BasCustomer basCustomer = bcService.getById(zrkUserCustomer.getCustomerId());
				if(null!=basCustomer) {
					//将客户分配状态改为已分配，防止重复分配该客户
					basCustomer.setIsAllocated(2);
					bcService.updateById(basCustomer);
				}
				BasCustomer customer = bcService.getById(userCustomer.getCustomerId());
				if(null!=customer) {
					//将客户分配状态还原为未分配
					customer.setIsAllocated(1);
					bcService.updateById(customer);
				}
				userCustomer.setCustomerId(zrkUserCustomer.getCustomerId());
			}
			userCustomer.setDisType(1);
			return this.updateById(userCustomer);
		}
		return false;
	}

	@Override
	@Transactional
	public boolean removeUserCustomer(String id) {
		// TODO Auto-generated method stub
	    ZrkUserCustomer zuc = this.getById(id);
		if(null != zuc) {
			BasCustomer basCustomer = bcService.getById(zuc.getCustomerId());
		    if(basCustomer!=null) {
		    	basCustomer.setIsAllocated(1);
			    bcService.updateById(basCustomer);
		    }
		    return this.removeById(id);
		}
		return false;
	}

	@Override
	@Transactional
	public boolean removeBatchUserCustomer(String ids) {
		// TODO Auto-generated method stub
		List<String> idList = Arrays.asList(ids.split(","));
		List<ZrkUserCustomer> cList = this.listByIds(idList);
		List<String> customerIdList = new ArrayList<>();
		for (ZrkUserCustomer zrkUserCustomer : cList) {
			customerIdList.add(zrkUserCustomer.getCustomerId());
		}
	    if(0 != customerIdList.size()) {
	    	List<BasCustomer> cusList = this.bcService.listByIds(customerIdList);
	    	if(null != cusList && 0 != cusList.size()) {
	    		for (BasCustomer basCustomer : cusList) {
	    			basCustomer.setIsAllocated(1);
				}
	    		bcService.updateBatchById(cusList);
	    	}
		}
		return this.removeByIds(idList);
	}

	@Override
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response,
			Class<ZrkUserCustomer> clazz) {
		// TODO Auto-generated method stub
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ZrkUserCustomer> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
                List<String> customerIdList = Lists.newArrayList();
                if(list!=null && list.size()>0) {
                	for(ZrkUserCustomer uc:list) {
                		if(CollUtil.contains(customerIdList, uc.getCustomerId())) {
                			BasCustomer bc = bcService.getById(uc.getCustomerId());
                			return Result.error("文件导入失败:" + bc.getName() + "在Excel列表中重复出现");
                		}
                		customerIdList.add(uc.getCustomerId());
                		uc.setDisType(1);
                	}
                	List<ZrkUserCustomer> ucList = this.list();
                	if(ucList!=null && ucList.size()>0) {
                		for(ZrkUserCustomer uc:ucList) {
                			if(CollUtil.contains(customerIdList, uc.getCustomerId())) {
                    			BasCustomer bc = bcService.getById(uc.getCustomerId());
                    			return Result.error("文件导入失败:" + bc.getName() + "已分配，不可重复分配");
                    		}
                		}
                	}
                	List<BasCustomer> bcList = bcService.listByIds(customerIdList);
                	if(bcList!=null && bcList.size()>0) {
                		for(BasCustomer bc:bcList) {
                			bc.setIsAllocated(2);
                		}
                		bcService.updateBatchById(bcList);
                	}
                }
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                this.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
	}

}
